import os,tempfile,shutil,commands
import pickle
import sys
import time
from crvclient import doSetUntilDone

inf=open(sys.argv[1],"r")

vmid=pickle.load(inf)
serverstr=pickle.load(inf)
serverhostname=pickle.load(inf)

MetaDataProvided=False

while not MetaDataProvided:

    cmdstr="curl -s \"%s/getVMAttr?vmid=%s&name=MetaDataProvided\""%(serverstr,vmid)

    (status,output)=commands.getstatusoutput(cmdstr)

    print "Running command=%s, status=%d, output=%s"%(cmdstr,status,output)
    if output=="True":
        MetaDataProvided=True

    time.sleep(5)
    
#now obtain metadata
cmdstr="curl -s \"%s/getVMAttr?vmid=%s&name=MetaData\""%(serverstr,vmid)
(status,output)=commands.getstatusoutput(cmdstr)
print "Running command=%s, status=%d, output=%s"%(cmdstr,status,output)

#Metadata will be the result from "tar cz certfiles|base64 -w 0"
#save it somewhere


metadata=output

base64file=tempfile.gettempdir()+"metadata.tgz.base64"

ouf=open(base64file,"w")
ouf.write(metadata)
ouf.close()

try:
    os.makedirs("/etc/puppet")
except:
    pass

cmdstr="base64 -d -w 0 %s|tar zx -C /etc/puppet/"%(base64file)
(status,output)=commands.getstatusoutput(cmdstr)
print "Running command=%s, status=%d, output=%s"%(cmdstr,status,output)

cmdstr='/etc/init.d/rsyslog start'
(status,output)=commands.getstatusoutput(cmdstr)
print "Running command=%s, status=%d, output=%s"%(cmdstr,status,output)

#Infinite loop which will take care of running puppet
#while True:

    #if need to run
    #    wget getVMAttr("needrun")
    
    #    get from server what roles are being applied to this VM
    #    activeroles=[xx,x,x,x,x]
    
    #    run puppet once

    #    if puppet run success
    #        set all activeroles success
    #    else
    #        set all activeroles fail

    #sleep for a while
#    time.sleep(1)


cmdstr='puppetd --genconfig --runinterval=30 --rrdinterval=30 --splaylimit=30 --server=%s | grep -v "genconfig" > /etc/puppet/puppet.conf' % serverhostname
(status,output)=commands.getstatusoutput(cmdstr)
print "Running command=%s, status=%d, output=%s"%(cmdstr,status,output)

cmdstr='/etc/init.d/puppet restart'
(status,output)=commands.getstatusoutput(cmdstr)
print "Running command=%s, status=%d, output=%s"%(cmdstr,status,output)
